

import 'dart:io' as IO;

import 'package:fget_file/config_model.dart';
import 'package:fget_file/file_model_entity.dart';
import 'package:fget_file/generated/json/base/json_convert_content.dart';
import 'package:flutter/material.dart';
import 'fget_file.dart';
import 'package:universal_platform/universal_platform.dart';

/// <summary>
/// todo: 文件选择页面
/// dateTime：2021/9/18 15:34
/// filePath：lib/FgetFilePage.dart
/// desc: 目前仅支持 Android ，ios可以选择使用file_picker
/// <summary>
typedef IndexedWidgetBuilder = Widget Function();
class FgetFilePage extends StatefulWidget {
  /// todo：配置
  ConfigModel configModel = ConfigModel();
  /// todo：选中的回调
  Function(List<FileModelData>) callback;
  /// todo：自定义视图
  /// bool是数据加载状态,FileModelEntity 是加载的数据
  Widget Function(FileModelEntity,bool) build;
  /// todo：指定路径查询
  String path;

  FgetFilePage({Key key,@required this.configModel, this.callback,this.build,this.path}) ;

  @override
  _FgetFilePageState createState() => _FgetFilePageState();
}

class _FgetFilePageState extends State<FgetFilePage> {

  /// todo：选择的数据
  List<FileModelData> selectData = [];

  /// todo：数据
  FileModelEntity listData = FileModelEntity()..data = [];

  /// todo：模态框控制器
  bool loading = true;

  /// todo：底部通知
  showMsg(msg){
    ScaffoldMessenger.of(context).hideCurrentSnackBar();
    ScaffoldMessenger.of(context).showSnackBar( SnackBar( content: Text("$msg"), ),);
  }

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    /// todo：页面渲染完后再加载数据
    WidgetsBinding.instance.addPostFrameCallback((mag) async => getDate());
  }

  /// todo：加载数据
  getDate() async{
    if(UniversalPlatform.isAndroid) listData = JsonConvert.fromJsonAsT(await FgetFile.files(type: widget.configModel.types,path: widget.configModel.path));

    // 防止未加载完时进行setState造成内存泄漏
    if(mounted) setState(() => loading = false);
  }

  @override
  Widget build(BuildContext context) {
    return Builder(builder: (context){
      return widget.build != null ? widget.build(listData,loading) :  _buildContent();
    });
  }

  // 列表子项
  _checkTitleItem(context,position){
    return CheckboxListTile(
      value: selectData.contains(listData.data[position]),
      onChanged: (newValue) {
        setState(() {
          if(!selectData.contains(listData.data[position])){
            if(selectData.length == widget.configModel.max) return showMsg("最大可选${widget.configModel.max}个文件");
            selectData.add(listData.data[position]);
          }else{
            selectData.remove(listData.data[position]);
          }
        });
      },
      title: Container(
        height: 65,
        child: Row(
          children: [
            _imageType(listData.data[position].filePath),
            SizedBox(width: 10,),
            Expanded(child: Column(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Text('${listData.data[position].fileName}',
                  style: TextStyle(fontSize: 16,color: Colors.grey[800],),overflow: TextOverflow.ellipsis,maxLines: 2,
                ),

                Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: [
                    Text('${listData.data[position].fileDate}',style: TextStyle(fontSize: 13,color: Colors.grey[800],)),
                    Text('  ${listData.data[position].fileSize}kb',maxLines: 1,overflow: TextOverflow.ellipsis,style: TextStyle(fontSize: 13,color: Colors.grey[800]))
                  ],
                ),
              ],
            ),),
          ],
        ),
      ),
      dense: true,
      // secondary: Image.file(File(listData.data[position].filePath),fit: BoxFit.cover,width: 50,height: 50,),
      // secondary: Image.asset("images/word.png",package: "fget_file",),
      selected: true,
      checkColor: Colors.white,
      activeColor: Colors.grey[800],
      controlAffinity: ListTileControlAffinity.platform,
    );
  }

  // 加载中模态框
  _loadWidget(){
    return Positioned(
      width: MediaQuery.of(context).size.width,
      height: MediaQuery.of(context).size.height,
      child: Container(
        color: Color(0x2020212),
        child: Center(
          child: ClipRRect(
            borderRadius: BorderRadius.circular(15),
            child: Container(
              width: 100,
              height: 100,
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.center,
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  CircularProgressIndicator(color: Colors.white,),
                  Text("正在加载",style:  TextStyle(fontSize: 16,color: Colors.white,),),
                ],
              ),
              color: Colors.grey[800],
            ),
          ),
        ),
      ),
    );
  }

  // 返回图标
  _imageType(filePath) {
    String temp = filePath.substring(filePath.lastIndexOf(".")+1,filePath.length).toLowerCase();

    if(temp=="png" || temp=="jpg" || temp=="jpeg"){
      return Image.file(IO.File(filePath),fit: BoxFit.cover,width: 50,height: 50,);
    }
    if(temp=="pdf"){
      return Image.asset("images/Pdf.png",package: "fget_file",fit: BoxFit.cover,width: 50,height: 50,);
    }
    if(temp=="doc" || temp=="docx"){
      return Image.asset("images/word.png",package: "fget_file",fit: BoxFit.cover,width: 50,height: 50,);
    }
    if(temp=="xlxs" || temp=="xlx"){
      return Image.asset("images/excel.png",package: "fget_file",fit: BoxFit.cover,width: 50,height: 50,);
    }
    return Image.asset("images/outher.png",package: "fget_file",color: Colors.grey,fit: BoxFit.cover,width: 50,height: 50,);
  }

  // 文件选择页面主体
  _buildContent() {
    return Scaffold(
      backgroundColor: Colors.white,
      appBar: AppBar(
        leading: Center(
          child: IconButton(onPressed: ()=> Navigator.pop(context), icon: Icon(Icons.chevron_left,color: Colors.grey[800],size: 30,),),
        ),
        title: Text("选择文件(${listData.data.length})",style: TextStyle(fontSize: 16,color: Colors.grey[800]),),
        centerTitle: true,
        backgroundColor: Colors.white,
        elevation: 0.5,
        actions: [
          Center(
            child: TextButton(
              onPressed: () {
                if(selectData.length == 0) return showMsg("未选择文件");
                widget.callback(selectData);
                Navigator.pop(context);
              },
              child: Text("选择(${selectData.length}/${widget.configModel.max})",style:  TextStyle(fontSize: 16,color: Colors.grey[800]),),
            ),
          ),
        ],
      ),
      body: Stack(
        children: [
          SizedBox(
            width: MediaQuery.of(context).size.width,
            height: MediaQuery.of(context).size.height,
            child: ListView.separated(
              shrinkWrap: true,
              physics: BouncingScrollPhysics(),
              //分割线构建器
              separatorBuilder: (BuildContext context, int index) => Divider(height: 5, color: Colors.grey[350]),
              itemBuilder: (BuildContext context, int position) => _checkTitleItem(context,position),
              itemCount: listData.data == null ? 0 : listData.data.length,
            ),
          ),
          loading ? _loadWidget():SizedBox(),
        ],
      ),
    );
  }
}
